package com.example.a15787.weather_zyy_1235;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.support.v4.app.Fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class WeatherFragment extends Fragment {
    private TextView tvCity, tvTemperature, tvHumidity, tvPm25, tvWind, tvTime;
    private Spinner citySpinner;
    private WeatherResponse weatherResponse;
    private List<String> cityNames = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_main, container, false);
        setupViews(view);
        // 这里需要重新加载天气数据，你可以根据实际情况修改
        // loadWeatherData();
        return view;
    }

    private void setupViews(View view) {
        tvCity = view.findViewById(R.id.tvCity);
        tvHumidity = view.findViewById(R.id.tvHumidity);
        tvPm25 = view.findViewById(R.id.tvPm25);
        tvTime = view.findViewById(R.id.tvTime);
        tvWind = view.findViewById(R.id.tvWind);
        tvTemperature = view.findViewById(R.id.tvTemperature);
        citySpinner = view.findViewById(R.id.citySpinner);
        citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                updateWeatherUIForCity(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    private void updateWeatherUIForCity(int position) {
        WeatherResponse.City city = weatherResponse.cities.get(position);
        tvCity.setText("当前城市：" + city.getCityName());
        List<WeatherResponse.Forecast> forecasts = city.getWeatherForecast();
        if (!forecasts.isEmpty()) {
            WeatherResponse.Forecast firstForecast = forecasts.get(0);
            tvTemperature.setText("当前温度：" + firstForecast.getTemperature().getMin() + " ~ " + firstForecast.getTemperature().getMax() + "℃");
            tvHumidity.setText("湿度：" + firstForecast.getHumidity() + "%");
            tvPm25.setText("PM2.5：" + String.format("%.1f", firstForecast.getPm25()));
            tvWind.setText("风速：" + firstForecast.getWind());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String currentTime = sdf.format(new Date());
            tvTime.setText("当前时间：" + currentTime);
        }
    }

}